import { ipcMain, BrowserWindow, app } from 'electron'
//获取那个窗口点击了按钮
function getClickedWindow(event: any) {
  return BrowserWindow.fromWebContents(event.sender)
}
//窗口最小化
function minimizeWindow(event: any) {
  const window = getClickedWindow(event)
  if (window) {
    window.minimize()
  }
}
//窗口最大化
function maximizeWindow(event: any) {
  const window = getClickedWindow(event)
  let isMax = false
  if (window) {
    if (window.isMaximized()) {
      window.unmaximize()
      isMax = false
    } else {
      window.maximize()
      isMax = true
    }
  }
  return isMax
}
//窗口关闭
function closeWindow(event: any) {
  const window = getClickedWindow(event)
  if (window) {
    //彻底关闭
    //判断是否是最后一个窗口
    const windows = BrowserWindow.getAllWindows()
    if (windows.length === 1) {
      //是最后一个窗口，关闭应用
      app.quit()
    } else {
      window.close()
    }
  }
}
interface WindowConfig {
  size?: [number, number]
  position?: [number, number]
}
//修改窗口配置信息
function setWindowConfig(event: any, config: WindowConfig) {
  const window = getClickedWindow(event)
  if (window&&!window.isDestroyed()) {
    //如果有配置信息就修改窗口配置信息没有就默认当前窗口大小
    const [width, height] = config.size || window.getSize()
    const [position, positionY] = config.position || window.getPosition()
    window.setSize(width, height)
    window.setPosition(window.getPosition()[0] - position, window.getPosition()[1] - positionY)

  }

return getLocationInformation(event)

}
//坐标信息
function getLocationInformation(event: any) {
  const window = getClickedWindow(event)
  if (window) {
    return window.getPosition()
  }
  return [0, 0]
}

function tool() {
  ipcMain.on('minimize-window', minimizeWindow)
  ipcMain.handle('maximize-window', maximizeWindow)
  ipcMain.on('close-window', closeWindow)
  ipcMain.handle('set-window-config', setWindowConfig)
  ipcMain.handle('get-location-information', getLocationInformation)
}
export default {
  tool
}
